let express = require('express')
let fs = require('fs').promises
const JWT = require('simple-jwt');
const header = {
  typ: 'JWT',
  alg: 'HS512'
};
const secret = 'secret';
let bodyParser = require('body-parser')
let app = express();
app.use(bodyParser.urlencoded({
  extended: false
}))
app.use(bodyParser.json())
app.use(express.static('./assets'))

app.use(function (req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', "*") // 设置响应头 支持跨域
  res.setHeader("Access-Control-Allow-Headers", 'Content-Type,Content-Length,Authorization, Accept,X-Requested-With,account,Authorization,a,test_token')
  // 所有的请求 从过来到离开 中间都会执行 中间件
  next()
})
app.listen(9000, function () {
  console.log("服务起于9000")
})
app.use(async function (req, res, next) {
  //  负责读取user  然后放到请求对象中
  let userStr = await fs.readFile('./json/user.json', 'utf-8')
  req.userAry = JSON.parse(userStr)

  // 推荐
  let tuijian = await fs.readFile('./json/tuijian.json', 'utf-8')
  req.tuijianAry = JSON.parse(tuijian)

  // 轮播图
  let swiper = await fs.readFile('./json/swiper.json', 'utf-8')
  req.swiperAry = JSON.parse(swiper)

  //热门搜索
  let hot = await fs.readFile('./json/hot.json', 'utf-8')
  req.hotAry = JSON.parse(hot)

  //主题
  let theme = await fs.readFile('./json/theme.json', 'utf-8')
  req.themeAry = JSON.parse(theme)

  //壁纸
  let wallpaper = await fs.readFile('./json/wallpaper.json', 'utf-8')
  req.wallpaperAry = JSON.parse(wallpaper)

  //原创
  let original = await fs.readFile('./json/original.json', 'utf-8')
  req.originalAry = JSON.parse(original)

  //头像
  let headImg = await fs.readFile('./json/headImg.json', 'utf-8')
  req.headImgAry = JSON.parse(headImg)

  //表情
  let expression = await fs.readFile('./json/expression.json', 'utf-8')
  req.expressionAry = JSON.parse(expression)

  // 影视
  let movies = await fs.readFile('./json/movies.json', 'utf-8')
  req.moviesAry = JSON.parse(movies)

  // 动漫
  let comic = await fs.readFile('./json/comic.json', 'utf-8')
  req.comicAry = JSON.parse(comic)

  // 爱豆
  let idol = await fs.readFile('./json/idol.json', 'utf-8')
  req.idolAry = JSON.parse(idol)

  // 动图
  let gif = await fs.readFile('./json/gif.json', 'utf-8')
  req.gifAry = JSON.parse(gif)

  // 文字
  let words = await fs.readFile('./json/words.json', 'utf-8')
  req.wordsAry = JSON.parse(words)

  // 素材
  let sucai = await fs.readFile('./json/sucai.json', 'utf-8')
  req.sucaiAry = JSON.parse(sucai)

  //萌宠
  let cutePet = await fs.readFile('./json/cutePet.json', 'utf-8')
  req.cutePetAry = JSON.parse(cutePet)

  //绘画
  let painting = await fs.readFile('./json/painting.json', 'utf-8')
  req.paintingAry = JSON.parse(painting)

  //手作
  let hand = await fs.readFile('./json/hand.json', 'utf-8')
  req.handAry = JSON.parse(hand)

  //时尚
  let fashion = await fs.readFile('./json/fashion.json', 'utf-8')
  req.fashionAry = JSON.parse(fashion)

  //美妆
  let beauty = await fs.readFile('./json/beauty.json', 'utf-8')
  req.beautyAry = JSON.parse(beauty)

  //婚礼
  let wed = await fs.readFile('./json/wed.json', 'utf-8')
  req.wedAry = JSON.parse(wed)

  //美食
  let food = await fs.readFile('./json/food.json', 'utf-8')
  req.foodAry = JSON.parse(food)

  //家居
  let jiaju = await fs.readFile('./json/jiaju.json', 'utf-8')
  req.jiajuAry = JSON.parse(jiaju)

  //旅行
  let travel = await fs.readFile('./json/travel.json', 'utf-8')
  req.travelAry = JSON.parse(travel)

  //摄影
  let photo = await fs.readFile('./json/photo.json', 'utf-8')
  req.photoAry = JSON.parse(photo)

   // 详情
  let details = await fs.readFile('./json/details.json', 'utf-8')
  req.detailsAry = JSON.parse(details)

 

  next()
})

app.post('/register', function (req, res) {
  // 获取前端传递的用户名密码 然后存储到 json的user.json
  // 先读  在修改  修改完了在写入
  let res2 = req.userAry.some(item => item.name == req.body.name)
  if (res2) {
    res.send({
      code: 501,
      msg: "用户已存在"
    })
    return
  }
  let ary = req.userAry.concat(req.body)
  fs.writeFile('./json/user.json', JSON.stringify(ary), 'utf-8').then(data => {
    res.send({
      code: 200,
      msg: '恭喜注册成功'
    })
  })

})
app.post('/login', function (req, res) {
  // 获取前端传递的用户名密码 然后存储到 json的user.json
  // 先读  在修改  修改完了在写入
  let res2 = req.userAry.some(item => item.loginName == req.body.loginName && item.passwordMd5 == req.body.passwordMd5)
  if (res2) {
    // 证明可以登录
    const token = JWT.getToken(header, {
      userName: req.body.loginName,
      psw: req.body.passwordMd5,
    }, secret);
    res.send({
      code: 200,
      token: token
    })
  } else {
    res.send({
      code: 502,
      msg: '用户名密码不对'
    })
  }
})

function isLogin(req, res) {
  // true 登录； false没登陆
  let {
    payload
  } = JWT.decodeTokenHeaderAndPayload(req.headers.test_token)
  // 解析前端传过来的token  ; 校验是否是正常的登录状态
  console.log(payload)
  return req.userAry.some(item => item.name == payload.userName && item.psw == payload.psw)
}

// 推荐
app.get('/tuijian', function (req, res) {
  res.send({
    code: 200,
    data: req.tuijianAry
  })
})

// 轮播图
app.get('/swiper', function (req, res) {
  res.send({
    code: 200,
    data1: req.swiperAry
  })
})

// 热门搜索
app.get('/hot', function (req, res) {
  res.send({
    code: 200,
    data: req.hotAry
  })
})
// 主题
app.get('/theme', function (req, res) {
  res.send({
    code: 200,
    data: req.themeAry
  })
})
// 壁纸
app.get('/wallpaper', function (req, res) {
  res.send({
    code: 200,
    data: req.wallpaperAry
  })
})
// 原创
app.get('/original', function (req, res) {
  res.send({
    code: 200,
    data: req.originalAry
  })
})
// 头像
app.get('/headImg', function (req, res) {
  res.send({
    code: 200,
    data: req.headImgAry
  })
})
// 表情
app.get('/expression', function (req, res) {
  res.send({
    code: 200,
    data: req.expressionAry
  })
})
// 影视
app.get('/movies', function (req, res) {
  res.send({
    code: 200,
    data: req.moviesAry
  })
})
// 动漫
app.get('/comic', function (req, res) {
  res.send({
    code: 200,
    data: req.comicAry
  })
})
// 爱豆
app.get('/idol', function (req, res) {
  res.send({
    code: 200,
    data: req.idolAry
  })
})
// 动图
app.get('/gif', function (req, res) {
  res.send({
    code: 200,
    data: req.gifAry
  })
})
// 文字
app.get('/words', function (req, res) {
  res.send({
    code: 200,
    data: req.wordsAry
  })
})
// 素材
app.get('/sucai', function (req, res) {
  res.send({
    code: 200,
    data: req.sucaiAry
  })
})
// 萌宠
app.get('/cutePet', function (req, res) {
  res.send({
    code: 200,
    data: req.cutePetAry
  })
})
// 绘画
app.get('/painting', function (req, res) {
  res.send({
    code: 200,
    data: req.paintingAry
  })
})
// 手作
app.get('/hand', function (req, res) {
  res.send({
    code: 200,
    data: req.handAry
  })
})
// 时尚
app.get('/fashion', function (req, res) {
  res.send({
    code: 200,
    data: req.fashionAry
  })
})
// 美妆
app.get('/beauty', function (req, res) {
  res.send({
    code: 200,
    data: req.beautyAry
  })
})
// 婚礼
app.get('/wed', function (req, res) {
  res.send({
    code: 200,
    data: req.wedAry
  })
})
// 美食
app.get('/food', function (req, res) {
  res.send({
    code: 200,
    data: req.foodAry
  })
})
// 家居
app.get('/jiaju', function (req, res) {
  res.send({
    code: 200,
    data: req.jiajuAry
  })
})
// 旅行
app.get('/travel', function (req, res) {
  res.send({
    code: 200,
    data: req.travelAry
  })
})
// 摄影
app.get('/photo', function (req, res) {
  res.send({
    code: 200,
    data: req.photoAry
  })
})
// 详情
app.get('/details', function (req, res) {
  res.send({
    code: 200,
    data: req.detailsAry
  })
})


app.post('/add', (req, res) => {
  let ary = req.listAry;
  console.log('req.body', req.body)
  ary.push(req.body)
  fs.writeFile('./json/list.json', JSON.stringify(ary), 'utf-8').then(data => {
    res.send({
      code: 200,
      msg: 'ok'
    })
  })
  // res.send('ok')
})
app.get('/del', (req, res) => {
  // console.log(req, req.query.id)
  let ary = req.listAry.filter(item => item.id != req.query.id)
  fs.writeFile('./json/list.json', JSON.stringify(ary), 'utf-8').then(data => {
    res.send({
      code: 200,
      msg: 'ok'
    })
  })
})